<?php
class TimeUtil
{
    public static function timeDiff(string $start, string $end, string $format = '%Y-%M-%D %H:%I:%S')
    {
        if ($start && $end) {
            //$timeZone = new DateTimeZone('Asia/Shanghai');
            $timeA = new DateTime($start);
            $timeB = new DateTime($end);
            return $timeA->diff($timeB)->format($format);
        }
    }

    public static function timeCost(string $start, string $end)
    {
        if ($start && $end) {
            $timeA = new DateTime($start);
            $timeB = new DateTime($end);
            $format = '%y-%m-%d-%h-%i-%s';
            $timeUnitArr = ['%s年', '%s月', '%s天', '%s时', '%s分', '%s秒'];
            $timeArr = explode('-', $timeA->diff($timeB)->format($format));
            foreach ($timeArr as $k => $item) {
                if ((int) $item !== 0) {
                    break;
                }
                unset($timeArr[$k], $timeUnitArr[$k]);
            }
            return vsprintf(implode('', $timeUnitArr), $timeArr);
        }
    }
}
